
/**
 *事件管理总线
 * @author longbin
 *
 */
 class EventManager {

    private evt: egret.EventDispatcher;
    private listeners: { [key: string]: Object } = {};

    public constructor() {
        this.evt = new egret.EventDispatcher();
    }

    /**
     * 添加时间侦听
     * @param type
     * @param listener
     * @param thisObject
     * @param useCapture
     * @param priority
     */
    public addEventListener(type: string, listener: Function, thisObject: any, useCapture?: boolean, priority?: number): void {
        if (!this.listeners[type]) {
            this.listeners[type] = { value: 0 };
        } else {
            this.listeners[type]["value"]++;
        }
        this.evt.addEventListener(type, listener, thisObject, useCapture, priority);
    }

    /**
     * 移除事件侦听
     * @param type
     * @param listener
     * @param thisObject
     * @param useCapture
     */
    public removeEventListener(type: string, listener: Function, thisObject: any, useCapture?: boolean): void {
        if (this.listeners[type]) {
            this.listeners[type]["value"]--;
            if (this.listeners[type]["value"] <= 0) {
                delete this.listeners[type];
            }
        }
        this.evt.removeEventListener(type, listener, thisObject, useCapture);
    }

    /**当前仍在侦听的事件列表*/
    public getListenerList(): string[] {
        let list: string[] = [];
        for (var key in this.listeners) {
            list.push(key);
        }
        return list;
    }

    /**
     * 是否存在事件侦听
     * @param type
     */
    public hasEventListener(type: string): boolean {
        return this.evt.hasEventListener(type);
    }

    /**
     * 派发事件
     * @param event
     */
    public dispatchEvent(event: egret.Event): void {
        this.evt.dispatchEvent(event);
    }

    /**
     * 侦听一次则自动移除的事件
     * @param type
     * @param listener
     * @param thisObject
     * @param useCapture
     * @param priority
     */
    public once(type: string, listener: Function, thisObject: any, useCapture?: boolean, priority?: number): void {
        this.evt.once(type, listener, thisObject, useCapture, priority);
    }

    public willTrigger(type: string): boolean {
        return this.evt.willTrigger(type);
    }

    /**
     * 派发一个指定参数的事件
     * @param type
     * @param bubbles
     * @param data
     */
    public dispatchEventWith(type: string, bubbles?: boolean, data?: any): boolean {
        return this.evt.dispatchEventWith(type, bubbles, data);
    }

}
